from flask import Flask
import logging
import os
import errno
from utils.loghandler import MultiProcessTimedRotatingFileHandler


LOG_DIR = 'log'


def get_logger(name, path='', file_name='serveing.log', when='H', interval=1, backupCount=30):
    formatter = logging.Formatter(
        fmt='[%(asctime)s][%(name)s][%(levelname)s] => %(message)s',
        datefmt="%Y-%m-%d  %H:%M:%S %a"
        )
    logger = logging.getLogger(name)
    logger.setLevel(logging.INFO)
    if not os.path.exists(LOG_DIR + path):
        try:
            os.makedirs(LOG_DIR + path)
        except OSError as e:
            if e.errno != errno.EEXIST:
                raise
    logfile = os.path.join(LOG_DIR + path, file_name)
    handler = MultiProcessTimedRotatingFileHandler(
        filename=logfile,
        when=when,
        interval=interval,
        backupCount=backupCount,
        encoding='utf-8',
        delay=False,
        utc=True)
    handler.setFormatter(formatter)
    logger.addHandler(handler)
    return logger


def create_app():
    # 创建Flask对象
    app = Flask(__name__)
    # 注册蓝图
    from server.api import api_v1
    app.register_blueprint(api_v1)
    return app
